package org.lhh.server.core.codec.directory;

import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.lhh.server.common.utils.PropertiesUtil;
import org.lhh.server.core.repository.EtlRepository;
import org.pentaho.di.repository.RepositoryDirectory;
import org.pentaho.di.repository.RepositoryDirectoryInterface;
import org.pentaho.di.repository.StringObjectId;

import java.util.List;

/**
 * @author 辉仔
 * @since 2019-06-16
 */
@Data
public class RepositoryDirectoryCodec {

    private String id;

    private String pId;

    private String name;

    private boolean open = true;

    private List<RepositoryDirectoryCodec> children;

    public static RepositoryDirectoryCodec encode(RepositoryDirectory repositoryDirectory) {
        RepositoryDirectoryCodec repositoryDirectoryCodec = new RepositoryDirectoryCodec();
        repositoryDirectoryCodec.setId(repositoryDirectory.getObjectId().getId());
        RepositoryDirectoryInterface parent = repositoryDirectory.getParent();
        repositoryDirectoryCodec.setPId(parent == null || parent.getObjectId() == null ? null : parent.getObjectId().getId());
        repositoryDirectoryCodec.setName(parent == null ?
                StringUtils.isNotEmpty(PropertiesUtil.getString("directory_home")) ?
                        PropertiesUtil.getString("directory_home") : "/" : repositoryDirectory.getName());
        return repositoryDirectoryCodec;
    }

    public static RepositoryDirectory decode(RepositoryDirectoryCodec repositoryDirectoryCodec) {
        RepositoryDirectory repositoryDirectory = new RepositoryDirectory();
        repositoryDirectory.setParent(EtlRepository.getDirectory(new StringObjectId(repositoryDirectoryCodec.getPId())));
        repositoryDirectory.setName(repositoryDirectoryCodec.getName());
        repositoryDirectory.setObjectId(new StringObjectId(repositoryDirectoryCodec.getId()));
        return repositoryDirectory;
    }
}
